// Globals
var correctAnswers = new Object;
var allImages = new Object;
var firstUnits = new Object;
var secondUnits = new Object;
var allConversions = new Object;
var total =0;

function generateAllQuestions() {
	
	//generateQuestion(id, side, startValue, startRange, endRange, steps, question_text, units, correct_answer_int,correct_answer_text, image_name, second_id, second_id_conversion, second_units, secondStartValue, roundSecond)
	
	generateQuestion(1, "left", 0, 0, 3000, 100, "How heavy is this glass beer mug?", "grams", 1300 ,"1300 grams / 2.86 pounds", "beer.jpg", 1000, 0.00220462, "pounds", "0.00", "false");
	generateQuestion(2, "right", 1, 0, 100, 5, "what percentage of the pie chart is colored blue?", "%", 35 ,"35%", "pie.png", "null", 1, "null", "null", "null");
	generateQuestion(3, "left", 1, 0, 100, 10, "How tall is this Ferris wheel?", "meters", 60 ,"60 meters / 197 feet", "wheel.png", 1003, 3.280839895, "feet", "3", "true");
	generateQuestion(4, "right", 1, 0, 60, 1, "How many Fuze Tea Bottles are in the picture?", "", 51 ,"51", "fuzetea.jpg", "null", 1, "null", "null", "null");
	generateQuestion(5, "left", 1, 0, 150000, 100, "How many people are in the picture?", " people", 98787 ,"97,787 people", "campnu.jpg", "null", 1, "null", "null", "null");
	generateQuestion(6, "right", 1, 0, 50, 0.10, "Evaluate the expression", "~", 12 ,"12~", "sqrt.png", "null", 1, "null", "null", "null");
	generateQuestion(7, "left", 1, 0, 100, 1, "What precent of earth is water?", "%", 71 ,"71.11%", "earth.jpg", "null", 1, "null", "null", "null");
	generateQuestion(8, "right", 1, 0, 4000, 10, "what is the diameter of this mine?", "meters", 1200 ,"1200 meters / 3900 feet", "mine.jpg", 1008, 3.280839895, "feet", "3", "true");
	generateQuestion(9, "left", 1, 0, 200, 1, "How many letters are in the picture?", "letters", 155 ,"155 letters", "letters.jpg", "null", 1, "null", "null", "null");
	generateQuestion(10, "right", 0, 0, 100, 1, "How heavy is this fish?", "kg", 73 ,"73 kg / 161 pounds", "fish.jpg", 1010, 2.20462, "pounds", "0", "true");
	generateQuestion(11, "left", 1, 0, 4000, 10, "How many pages are in these books combined?", "pages", 1670 ,"1670 pages", "books.jpg", "null", 1, "null", "null", "null");
}





// second_id = another field to update the slider visually
// second_id_conversion = convert from unit to unit. for example from meter to feet, use 3.280839895
function create_question(id, startValue, startRange, endRange, steps, second_id, second_id_conversion, secondStartValue, roundSecond) {
	
	total = total + 1;
	
	$("#slider_value_" + id).html(startValue);
	$("#slider_value_" + second_id).html(secondStartValue);
	
	$( "#slider_" + id ).noUiSlider({range: [startRange, endRange], start: 1, handles: 1, step: steps, slide: function() {
		
		$("#slider_value_" + id).html(Math.round($("#slider_" + id).val()));
		
		if (second_id != "null") {
			
			
			
			if (roundSecond == "false") {
				var x = Math.round($("#slider_" + id).val()) * second_id_conversion;
				x = Math.floor(x * 100) / 100;
				$("#slider_value_" + second_id).html(x.toFixed(2));
			}
			else {
				$("#slider_value_" + second_id).html(Math.floor(Math.round($("#slider_" + id).val()) * second_id_conversion));
			}
		}
		
		$("#submit_button_" + id).attr("disabled", false);
	}});
}

function submit(id) {
	
	$("#question_div_" + id).fadeOut( function() {
		$("#after_submit_" + id).fadeIn();
	});
	
	var answer = Math.round($("#slider_" + id).val());
	
	report_result(id, answer);
	
	calculate_user_score(answer, id);
}

function generateQuestion(id, side, startValue, startRange, endRange, steps, question_text, units, correct_answer_int,correct_answer_text, image_name, second_id, second_id_conversion, second_units, secondStartValue, roundSecond) {
	
	correctAnswers[id] = correct_answer_int;
	allImages[id] = image_name;
	firstUnits[id] = units;
	secondUnits[id] = second_units;
	allConversions[id] = second_id_conversion;
	
	next_id = id + 1;
	
	question_data = {
	            id: id,
	            second_id: second_id,
	            question_text: question_text,
	            units: units,
	            second_units: second_units,
	            correct_answer: correct_answer_text,
	            image_name:  image_name,
	            next_id: next_id
	 };
	
	 if (side == "right") {
		 
		 if (second_id == "null") {
			 question = ich.right_single_template(question_data);
		 }
				 
		 else {
			question = ich.right_double_template(question_data);
		 }
	 }
	 else {
		 if (second_id == "null") {
			 question = ich.left_single_template(question_data);
		 }
		 else {
			 question = ich.left_double_template(question_data);
		 }
	 }
	 
	 $("#main_content").append(question);
	 
	 create_question(id, startValue, startRange, endRange, steps, second_id, second_id_conversion, secondStartValue, roundSecond);
}

$( document ).ready(function() {
	
	// DO NOT REMOVE - Making the templates work
	ich.refresh();
	
	generateAllQuestions();
	
	// Change the last arrow to subscribe
	num_of_arrow = total + 1;
	$("#arrowto" + num_of_arrow).attr("href", "#bottom");
	$("#arrowto" + num_of_arrow).removeClass("arrow");
	
	// Tell DB About your session
	$.post("/db_insert", {new_session: 'new_session'}, function (data) {
		
		$("#session_id").val(data);
	});

	$('a.arrow').click(function(){
	    $('html, body').animate({
	        scrollTop: $( $.attr(this, 'href') ).offset().top
	    }, 500);
	    return false;
	});
	
	$("a[href='#bottom']").click(function() {
		  $("html, body").animate({ scrollTop: $(document).height() }, "slow");
		  return false;
		});

	$("a[href='#top']").click(function() {
		  $("html, body").animate({ scrollTop: 0 }, "slow");
		  return false;
		});

		
		// jQuery extension to support star ratings.	
	$.fn.stars = function(value) {
		//return $(this).each(function(value) {
			// Get the value
			var val = value; //parseFloat($(this).html());
			// Make sure that the value is in 0 - 5 range, multiply to get width
            //var normalizedval = val*5/100
			//var size = Math.max(0, (Math.min(5, normalizedval))) * 256;
			var size = val * 128 /100;
            // Create stars holder
			
            //$("#showscore").html(0);
			// Replace the numerical value with stars
            $(this).children().animate(
                {
                    height:128-size
                },
                { 
                    duration: 1000,
                    step: function() {
                        //$("#showscore").html(100-Math.round($("span.stars span").height()*100/256));
                    }
                });
		//});
	};	

	// Bind "enter" key in subscription email input to the "subscribe" button
	$("#subscribe_email_bottom").keypress(function(event){
		if(event.keyCode == 13){
			event.preventDefault();
			$("#sendsubscribe").click();
		}
	});
	
    $("a , button").on("click",function() { report_click( $(this).attr('id') );});
});


function report_click(source) {
	
	var id = $("#session_id").val();
    
    _gaq.push(['_trackEvent', "Button", "click", source,1, true]); 
    
	$.post("/db_insert", {click: "click", source: source, id: id});
}

function report_result(type, result) {
	
	correct_answer = correctAnswers[type];
	
	$.post("/db_insert", {submit: "submit", type: type, result: result, correct_answer: correct_answer});
}

function subscribe_button() {
	
	
	
	//var email = $("#subscribe_email").val();
	
	email = $("#subscribe_email_bottom").val();
	
	
	if (IsEmail(email)) {
	
		$.post("/db_insert", {subscribe: "subscribe", email: email});
		
		$("#subscribe_form_bottom").hide();
		$("#subscrive_promise_bottom").hide();		
		$("#subscribe_thankyou_bottom").fadeIn();
	}
	else {
		$("#wrong_mail").html("Please insert a valid mail");
		$("#wrong_mail").show();
	}
}


function IsEmail(email) {
	  // var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	  var regex = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;

	  return regex.test(email);
}

function calculate_user_score(score, type) {
	
	$.post("/db_select", {user_score: "user_score", user_result: score, type: type}, function(data){
		
		// avg_beer user_beer
		var average  = data.split('#')[0];
		var better  = data.split('#')[1];
			
		generate_share(type, better);
		
		if (secondUnits[type] != "null") {
			
			// Converting the results
			var converted = average * allConversions[type];
			
			// Eliminate tons of 0.xxxxxxxxxxxxxxxxxxxx
			converted = Math.floor(converted * 100) / 100;
			
			$("#avg_" + type).html(average + " " + firstUnits[type] + " / " + converted.toFixed(2) + " " + secondUnits[type]);
			$(".user_score.user_" + type).html(better);
            $('.stars.user_' + type).stars(better);
		}
		else {
			
			$("#avg_" + type).html(average + " " + firstUnits[type]);
			$(".user_score.user_" + type).html(better);
            $('.stars.user_' + type).stars(better);
		}

	});
}

function generate_share(source, score) {
	
	gameimg = allImages[source];
	
	
	//var fb_href="http://www.facebook.com/sharer/sharer.php?s=100&p[url]=www.intumate.com&p[images][0]=http://intumate.com/img/intumate.png&p[title]=My%20score%20on%20Intumate!&p[summary]=My%20intuition%20is%20better%20than%20" + score + "%25%20of%20the%20rest%20of%20the%20world!%0A%0AThink%20you%20can%20do%20better?%20prove%20it.%0Ahttp://www.intumate.com";
	var tw_href="http://twitter.com/home?status=My%20intuition%20is%20better%20than%20" + score + "%25%20of%20the%20rest%20of%20the%20world!%0A%0AThink%20you%20are%20better?%20prove%20it.%0Ahttp://www.intumate.com";
	var fb_href="https://www.facebook.com/dialog/feed?app_id=568515256554117&display=popup&name=Better than " + score + "% of the rest of the world!" + "&link=http://www.intumate.com&redirect_uri=http://www.intumate.com/closewindow.html&picture=http://www.intumate.com/img/" + gameimg;
	
	$("#fb_share_" + source).attr("onclick", "myPopup('" + fb_href + "');");
	$("#tw_share_" + source).attr("onclick", "myPopup('" + tw_href + "');");
	
}

function myPopup(url) {
	window.open( url, "myWindow", "status = 1, height = 500, width = 360, resizable = 0" )
	}
	

